package com.org.platform.support.conponents;

import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author devg
 * @Date 2020/3/1 10:25
 */
@Slf4j
@Component
public class Lock {

  @Autowired
  private StringRedisTemplate stringRedisTemplate;

  public boolean lockKey(String key, long time, TimeUnit timeUnit) {
    return stringRedisTemplate.opsForValue().setIfAbsent(key,"1", time, timeUnit);
  }

  public boolean lockKey(String key) {
    return stringRedisTemplate.opsForValue().setIfAbsent(key,"1");
  }

  public void lockRealse(String key){
    stringRedisTemplate.delete(key);
  }

  public void lock(String key, long timeout, TimeUnit timeUnit) {
    boolean lock = false;
    while (!lock) {
      lock = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", timeout, timeUnit);
      try {
        Thread.sleep(500);
      } catch (InterruptedException ex) {
        log.error("getLock error", ex.getMessage());
      }
    }
  }

  public void releaseLock(String key) {
    stringRedisTemplate.delete(key);
  }
}
